package com.yimils.core.sys.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yimils.core.sys.dto.ReqAddUserRole;
import com.yimils.core.sys.entity.UserRoleEntity;
import com.yimils.core.sys.mapper.RoleMapper;
import com.yimils.core.sys.mapper.UserRoleMapper;
import com.yimils.core.sys.po.UserRoleDo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("userRoleService")
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRoleEntity> implements UserRoleService {
    @Autowired(required = false)
    private RoleMapper roleMapper;

    @Override
    public boolean addUserRole(ReqAddUserRole reqParams) {
        ArrayList<UserRoleEntity> collect = new ArrayList<>();
        for (Long roleId : reqParams.getRoleId()) {
            UserRoleEntity entity = new UserRoleEntity();
            entity.setUserId(reqParams.getUserId());
            entity.setRoleId(roleId);
            collect.add(entity);
        }
        return saveBatch(collect);
    }

    @Override
    public Long getHighestRoleId(Long userId) {
        QueryWrapper<UserRoleEntity> qw = new QueryWrapper<>();
        qw.lambda().eq(UserRoleEntity::getUserId, userId).orderByAsc(UserRoleEntity::getRoleId).last("limit 1");
        return getOne(qw).getRoleId();
    }

    @Override
    public List<UserRoleDo> getRolesByUserId(Long id) {
        return roleMapper.getRolesByUserId(id);
    }

    @Override
    public UserRoleEntity getRoleInType(Long userId, Integer type) {
        QueryWrapper<UserRoleEntity> qw = new QueryWrapper<>();
        qw.lambda().eq(UserRoleEntity::getUserId, userId).eq(UserRoleEntity::getType, type);
        return getOne(qw);
    }


}
